﻿using System;
using System.IO;
using __Ts.Core.Log;

namespace __Ts.Core.Plugin
{
    public class PluginDomain
    {
        private AppDomain appDomain;
        private IPlugin _plugin = null;

        public IPlugin GetPlugin()
        {
            //if (_plugin == null)
            //{
                RemoteLoader remObj = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap("__Ts.Core", "__Ts.Core.Plugin.RemoteLoader");
                _plugin = remObj.LoadPlugin(this.AssemblyPath);

                object o = _plugin.GetServices();

            //}
            return _plugin;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="assemblyPath"></param>
        public PluginDomain(string assemblyPath)
        {
            this.AssemblyPath = assemblyPath;

            if (appDomain == null)
                this.appDomain = CreateAppDomain(assemblyPath);
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            AppDomain.Unload(this.appDomain);
            this.appDomain = null;
        }
        /// <summary>
        /// 
        /// </summary>
        public string AssemblyPath
        {
            get;
            private set;
        }
        /// <summary>
        /// 
        /// </summary>
        public string FriendlyName
        {
            get { return this.appDomain.FriendlyName; }
        }
        /// <summary>
        /// 
        /// </summary>
        public int Id
        {
            get { return this.appDomain.Id; }
        }

        /// <summary>
        /// 创建程序域
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private AppDomain CreateAppDomain(string assemblyPath)
        {
            string filename = Path.GetFileNameWithoutExtension(assemblyPath);
            try
            {

                AppDomainSetup setup = new AppDomainSetup();
                setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                setup.ApplicationName = "Plugins_" + filename;
                setup.ShadowCopyFiles = "true";
                setup.ShadowCopyDirectories = Path.GetDirectoryName(assemblyPath);
                this.appDomain = AppDomain.CreateDomain("PluginDomain_" + filename, null, setup);

                Logger.Write(string.Format("创建了程序域{0}。", this.appDomain.FriendlyName));
            }
            catch (Exception ex)
            {
                Logger.Write("创建程序域失败：" + ex.Message);
            }
            return this.appDomain;
        }
    }
}
